package com.wans.guli.order.rabbitmq;

import com.rabbitmq.client.Channel;
import com.wans.guli.order.entity.OrderEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class OrderMessageReceiver {

    @RabbitListener(queues = "order.close")
    public void receiveOrderMessage(OrderEntity order, Channel channel, Message message) throws IOException {
        try {
            log.info("收到订单消息: {}", order);
            
            // 处理订单业务逻辑
            processOrder(order);
            
            // 手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            
        } catch (Exception e) {
            log.error("处理订单消息异常: {}", e.getMessage(), e);
            
            // 处理失败，拒绝消息并重新入队
            channel.basicNack(
                message.getMessageProperties().getDeliveryTag(), 
                false, 
                true // 重新入队
            );
        }
    }
    
    private void processOrder(OrderEntity order) {
        // 实现订单处理逻辑
        // 这里可能会调用库存服务、支付服务等
    }
}